// 数据管理页面JavaScript
let currentPage = 1;
const itemsPerPage = 10;
let allJobs = [];
let filteredJobs = [];

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadJobs();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 搜索功能
    document.getElementById('searchInput').addEventListener('input', handleSearch);
    
    // 新增按钮
    document.getElementById('addJobBtn').addEventListener('click', openAddModal);
    
    // 模态框关闭
    document.querySelector('.close-btn').addEventListener('click', closeModal);
    
    // 表单提交
    document.getElementById('jobForm').addEventListener('submit', handleFormSubmit);
    
    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        const modal = document.getElementById('jobModal');
        if (event.target === modal) {
            closeModal();
        }
    });
}

// 加载职位数据
async function loadJobs() {
    try {
        const response = await fetch('/api/jobs');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();

        allJobs = data.jobs;
        filteredJobs = [...allJobs];
        renderTable();
        renderPagination();
    } catch (error) {
        console.error('Error loading jobs:', error);
        showMessage('网络错误，请稍后重试', 'error');
    }
}

// 搜索处理
function handleSearch(event) {
    const searchTerm = event.target.value.toLowerCase();
    
    if (searchTerm === '') {
        filteredJobs = [...allJobs];
    } else {
        filteredJobs = allJobs.filter(job => 
            job.job_name.toLowerCase().includes(searchTerm) ||
            job.company_name.toLowerCase().includes(searchTerm) ||
            job.address.toLowerCase().includes(searchTerm)
        );
    }
    
    currentPage = 1;
    renderTable();
    renderPagination();
}

// 渲染表格
function renderTable() {
    const tbody = document.getElementById('jobsTableBody');
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const currentJobs = filteredJobs.slice(startIndex, endIndex);
    
    tbody.innerHTML = '';
    
    currentJobs.forEach(job => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${job.id}</td>
            <td>${job.job_name}</td>
            <td>${job.company_name}</td>
            <td>${job.salary}</td>
            <td>${job.address}</td>
            <td>${job.experience || '-'}</td>
            <td>${job.educational || '-'}</td>
            <td>
                <button class="btn btn-sm btn-secondary" onclick="editJob(${job.id})">编辑</button>
                <button class="btn btn-sm btn-danger" onclick="deleteJob(${job.id})">删除</button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 渲染分页
function renderPagination() {
    const pagination = document.getElementById('pagination');
    const totalPages = Math.ceil(filteredJobs.length / itemsPerPage);
    
    pagination.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    // 上一页
    if (currentPage > 1) {
        const prevBtn = createPageButton('上一页', currentPage - 1);
        pagination.appendChild(prevBtn);
    }
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            const pageBtn = createPageButton(i, i);
            if (i === currentPage) {
                pageBtn.classList.add('active');
            }
            pagination.appendChild(pageBtn);
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.className = 'pagination-ellipsis';
            pagination.appendChild(ellipsis);
        }
    }
    
    // 下一页
    if (currentPage < totalPages) {
        const nextBtn = createPageButton('下一页', currentPage + 1);
        pagination.appendChild(nextBtn);
    }
}

// 创建分页按钮
function createPageButton(text, page) {
    const button = document.createElement('button');
    button.textContent = text;
    button.className = 'pagination-btn';
    button.addEventListener('click', () => {
        currentPage = page;
        renderTable();
        renderPagination();
    });
    return button;
}

// 打开新增模态框
function openAddModal() {
    document.getElementById('modalTitle').textContent = '新增职位';
    document.getElementById('jobForm').reset();
    document.getElementById('jobId').value = '';
    document.getElementById('jobModal').style.display = 'block';
}

// 编辑职位
function editJob(id) {
    const job = allJobs.find(j => j.id === id);
    if (!job) return;
    
    document.getElementById('modalTitle').textContent = '编辑职位';
    document.getElementById('jobId').value = job.id;
    document.getElementById('jobName').value = job.job_name;
    document.getElementById('companyName').value = job.company_name;
    document.getElementById('salary').value = job.salary;
    document.getElementById('address').value = job.address;
    document.getElementById('experience').value = job.experience || '';
    document.getElementById('educational').value = job.educational || '';
    document.getElementById('jobDetail').value = job.job_detail || '';
    
    document.getElementById('jobModal').style.display = 'block';
}

// 删除职位
async function deleteJob(id) {
    if (!confirm('确定要删除这个职位吗？')) return;

    try {
        const response = await fetch(`/api/jobs/${id}`, {
            method: 'DELETE'
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        showMessage('删除成功', 'success');
        loadJobs();
    } catch (error) {
        console.error('Error deleting job:', error);
        showMessage('删除失败，请稍后重试', 'error');
    }
}

// 关闭模态框
function closeModal() {
    document.getElementById('jobModal').style.display = 'none';
}

// 处理表单提交
async function handleFormSubmit(event) {
    event.preventDefault();
    
    const formData = {
        job_name: document.getElementById('jobName').value,
        company_name: document.getElementById('companyName').value,
        salary: document.getElementById('salary').value,
        address: document.getElementById('address').value,
        experience: document.getElementById('experience').value,
        educational: document.getElementById('educational').value,
        job_detail: document.getElementById('jobDetail').value
    };
    
    const jobId = document.getElementById('jobId').value;
    const isEdit = jobId !== '';
    
    try {
        const url = isEdit ? `/api/jobs/${jobId}` : '/api/jobs';
        const method = isEdit ? 'PUT' : 'POST';
        
        const response = await fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        showMessage(isEdit ? '更新成功' : '添加成功', 'success');
        closeModal();
        loadJobs();
    } catch (error) {
        console.error('Error submitting form:', error);
        showMessage('网络错误，请稍后重试', 'error');
    }
}

// 显示消息
function showMessage(message, type) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    
    // 添加到页面
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}
